<?php

namespace app\admin\controller\lists;

use AlibabaCloud\SDK\Ocr\V20191230\Models\RecognizeBankCardAdvanceRequest;
use app\admin\model\buchang\Baoan;
use app\common\controller\Backend;
use fast\Http;
use think\Config as thconfig;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\Log;
use const http\Client\Curl\Versions\CURL;

// 1、这里只是以ocr下的RecognizeBankCard能力为例，其他能力请引入相应类目的包和相关类。包名可参考本文档上方的SDK包名称，能力名可参考对应API文档中的Action参数。例如您想使用通用分割，其文档为https://help.aliyun.com/document_detail/151960.html，可以知道该能力属于分割抠图类目，能力名称为SegmentCommonImage，那么您需要将代码中Ocr改为Imageseg，将RecognizeBankCard改为SegmentCommonImage。版本号V20191230如果有变化也需要修改。

use AlibabaCloud\SDK\Ocr\V20191230\Ocr;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ocr\V20191230\Models\RecognizeIdentityCardAdvanceRequest;
use AlibabaCloud\SDK\Ocr\V20191230\Models\RecognizeDrivingLicenseAdvanceRequest;


/**
 * 服务单录入查询需要的字段集合
 *
 * @icon fa fa-circle-o
 */
class One extends Backend
{

    /**
     * One模型对象
     * @var \app\admin\model\lists\One
     */
    protected $model = null;
    protected $relationSearch =true;
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\lists\One;
        $this->view->assign("statusList", $this->model->getStatusList());
        $admin = $this->auth->getUserInfo();
        $jigoudata = [''=>'请选择业务来源','直属业务'=>'直属业务','直接业务'=>'直接业务','分支机构'=>'分支机构','合作商'=>'合作商','查勘机构'=>'查勘机构','招商业务'=>'招商业务','合作业务 '=>'合作业务'];
        $this->view->assign('jigoudata', $jigoudata);
        $site = thconfig::get('site');
        $this->view->assign('chexing', $site['chexing']);
        $this->view->assign('xingzhi', $site['xingzhi']);
        $rule = Db::name('auth_group_access')->alias('a')->join('auth_group b','a.group_id = b.id')->where('a.uid',$admin['id'])->field('b.rules,a.group_id')->find();
        $rules = $rule['rules'];
        if($rules == '*'){
            $rules = Db::name('auth_rule')->column('id');
        }else{
            $rules = explode(',',$rule['rules']);
        }
        $this->rule = $rules;
        $this->group_id = $rule['group_id'];
        $status = 0;
        if(in_array(195,$rules)){
            $status = 1;
        }
        $this->assignconfig('status', $status);
        $sxstatus = false;
        if(in_array(241,$rules)){
            $sxstatus = 'like';
        }
        $this->assignconfig('sxstatus', $sxstatus);
        $zdstatus = 0;
        if(in_array(252,$rules)){
            $zdstatus = 1;
        }
        $this->assignconfig('zdstatus', $zdstatus);
        $this->assignconfig('rule', $rules);
        $this->assign('rule', $rules);
        $zuzhi = Db::name('zuzhi')->where('id',$admin['zuzhi'])->find();
        $pay_channel = pay_type($zuzhi);
        $this->view->assign('pay_channel', $pay_channel);
        $this->assign('admin', $admin);
        $this->assign('zuzhi', $zuzhi);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            $where0 = [];
            $admin = $this->auth->getUserInfo();
            $rule = $this->rule;
            if($admin['id'] != 1 && in_array(220,$rule)){
                $time_num = \think\Config::get('site.fwd_time');
                if($time_num){
                    $time = time()-7*86400;
                    $where0['yw_join_time'] = ['>',$time];
                }
            }
            //当前登录人组织
            $cateid = $admin['zuzhi'];
            if (isset($filter['zuzhi.name'])) {
                if($filter['zuzhi.name']) $zuzhi = $filter['zuzhi.name'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['zuzhi.name'],$op['zuzhi.name']);
            }
            if($admin['id'] == 1 && !isset($zuzhi)){
                $arr = [];
            }else{
                //有组织筛选就赋值给cateid
                if(isset($zuzhi) && $zuzhi){
                    $cateid = $zuzhi;
                }
                $date = Db::name('zuzhi')->where('delete_id',0)->select();
                //出理上下级关系
                $arr = $this->getSubs1($date,$cateid);
                //赋值给z_arr
                $arr[]=$cateid;
            }
            if($arr){
                $where0['one.yw_class'] = ['in',$arr];
            }

            if($this->group_id == 3){
                unset($where0);
                $where0['one.user_id']=$admin['id'];
            }
            $this->request->get(['filter'=>json_encode($filter,true)]);
            $this->request->get(['op'=>json_encode($op,true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(["zuzhi"])
                ->where($where)
                ->where($where0)
                ->order($sort, $order)
//                ->select();
                ->paginate($limit);

            foreach ($list as $row) {
                $row['sign'] = 0;
                $sign = Db::name('sign')->where('orderid',$row['id'])->find();
                if($sign){
                    $row['sign'] = 1;
                }
            }
            $all_main_free =  Db::name('list_one')
                ->alias('one')
                ->join('zuzhi zuzhi','one.yw_class = zuzhi.id','left')
                ->where($where)
                ->where($where0)
                ->group('one.id')->where('deletetime',)
                ->field('one.main_free,one.main_sum')
                ->select(false);
            $all = Db::query('select sum(c.main_free) as all_main_free,sum(c.main_sum) as all_main_sum from ('.$all_main_free.') as c');
            $all_main_free = round($all[0]['all_main_free'],2);
            $all_main_sum = round($all[0]['all_main_sum'],2);
            $result = array("total" => $list->total(), "rows" => $list->items(),'all_main_free'=>$all_main_free,'all_main_sum'=>$all_main_sum);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($status = 0)
    {
        $admin = $this->auth->getUserInfo();
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $site = thconfig::get('site');
        $count = Db::name('list_one')->where('yw_belonger',$admin['username'])->where('status',6)->where('deletetime',)->count();
        $luru_count = Db::name('list_one')->where('yw_belonger',$admin['username'])->where('status',5)->where('deletetime',)->count();
        if($count){
            if($luru_count > 0){
                $lv = bcmul(bcdiv($count,$luru_count,4),100,2);
            }else{
                $lv = $count*100;
            }
            if($lv > $site['tuitonglv']){
                $this->error('超过退统率，请先取消退统统计');
            }
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['car_is_new'] = isset($params['car_is_new']) ? $params['car_is_new'] : 2;
            $params['main_franchise'] = isset($params['main_franchise']) ? $params['main_franchise'] : 2;
            $params['main_ji'] = isset($params['main_ji']) ? $params['main_ji'] : 2;
            $params['dao_ji'] = isset($params['dao_ji']) ? $params['dao_ji'] : 2;
            $params['siji_ji'] = isset($params['siji_ji']) ? $params['siji_ji'] : 2;
            $params['ck_ji'] = isset($params['ck_ji']) ? $params['ck_ji'] : 2;
            $params['dw_ji'] = isset($params['dw_ji']) ? $params['dw_ji'] : 2;
            $params['main_name'] = isset($params['main_name']) ? $params['main_name'] : 2;
            $params['main_disan'] = isset($params['main_disan']) ? $params['main_disan'] : 2;
            $params['dao_name'] = isset($params['dao_name']) ? $params['dao_name'] : 2;
            $params['siji'] = isset($params['siji']) ? $params['siji'] : 2;
            $params['chengke'] = isset($params['chengke']) ? $params['chengke'] : 2;
            $params['dianwang'] = isset($params['dianwang']) ? $params['dianwang'] : 2;
            //1、获取本商户的最新进货单号
            $zancun = zancun("list_one", "tong_storage", "");
            $params['tong_storage'] = $zancun;
            $params['kehu_sumdiscount'] = $params['main_sumdiscount'];
            $urls = $params['file'];
            unset($params['file']);
            $params['status'] = 0;
            $params['car_register'] = strtotime($params['car_register']);
            $params['plan_strattime'] = strtotime($params['plan_strattime']);
            $params['plan_endtime'] = strtotime($params['plan_endtime']);
            $params['yw_join_time'] = time();
            $params['yw_enter_peo'] = $admin['username'];
//            $params['chexing_ci'] = $params['c-chexing_ci'];
//            unset($params['c-chexing_ci']);
//            $car_num = $params['car_num'];
//            $car_vin = $params['car_vin'];
//            $car_engine = $params['car_engine'];
//            $where = "car_num='{$car_num}' OR car_vin='{$car_vin}'";
//            if ($car_engine != "无") {
//                $where .= " OR car_engine='{$car_engine}'";
//            }
//            $dong_list = Db::name("list_one")->where($where)->where('deletetime',)->field('id,plan_endtime')->select();
//            $dong_error = false;
//            foreach ($dong_list as $item) {
//                if ($item['plan_endtime'] > $params['plan_strattime']) {
//                    $dong_error = true;
//                    break;
//                }
//            }
//            if ($dong_error) {
            // return ["status" => 0, "message" => "服务日期重叠"];
//            }
            $params['user_id'] = $admin['id'];
            $params['yw_handle'] = $admin['username'];
            //判断车架号是否符合服务
//            $isset = Db::name('list_one')->where('car_vin',$params['car_vin'])->where('deletetime',)->where('status','in',[0,1,2,3,4])->field('id,status,plan_endtime')->find();
            if($status == 1) {
                $isset = Db::name('list_one')->where('car_vin',$params['car_vin'])->where('deletetime',)->where('status','in',[3])->field('id,status,plan_endtime')->find();
                if($isset){
                        $this->error('该车正在服务中，不得重复添加');
                }
                $isset2 = Db::name('list_one')->where('car_vin',$params['car_vin'])->where('status',5)->field('id,status,plan_endtime')->select();
                foreach ($isset2 as $key => $value) {
                    if($value['plan_endtime']>time()){
                        $this->error('该车正在服务中，不得重复添加');
                    }
                }
                $isset3 = Db::name('list_one_old')->where('car_vin',$params['car_vin'])->where('status',5)->field('id,status,plan_endtime')->select();
                foreach ($isset3 as $key1 => $value1) {
                    if($value1['plan_endtime']>time()){
                        $this->error('该车正在服务中，不得重复添加3');
                    }
                }
            }
            if(!empty($params['learned_phone'])){
                $count = Db::name('list_one')->where('learned_phone',$params['learned_phone'])->where('deletetime',)->where('status','in',[0,1,2,3,4])->field('id,status,plan_endtime')->count();
                if($count > 2){
                    $this->error('当前手机号超过两次，不可录入');
                }
            }

            if($status == 1){
                $params['main_xiaoguan_bili'] = 0;
                $params['main_yunying_bili'] = 0;
                $params['main_netrate'] = 40;
                $params['status'] =1;
                $params['yw_hetong_time'] = time();
            }
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $result = db('list_one')->insertGetId($params);
            $id = $result;
            $newid = $id;
            $urls = explode(',', $urls);
            $count = count($urls);
            for ($i=0;$i<$count;$i++){
                $img['url'] = $urls[$i];
                $img['tong_id'] = $newid;
                $img['title'] = '';
                $img['updatetime'] = time();
                $res = db('tong_files')->insert($img);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('','',['id'=>$result]);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null,$status = 0)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['car_register'] = date('Y-m-d',$row['car_register']);
            if($row['plan_strattime'] < time()){
                $row['plan_strattime'] = date('Y-m-d', strtotime(' +1 day'));
                $row['plan_endtime'] = date('Y-m-d 23:59:59', strtotime(' +1 year'));;
            }
            $this->view->assign('row', $row);
            $row['yw_class'] = Db::name('zuzhi')->where('id',$row['yw_class'])->value('name');

            $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
            $this->assign('ren',$ren);


            $ying = db('tong_files')->where('tong_id',$ids)->column('url');
            $this->assign('file', implode(',',$ying));

            $yijian = db('yijian')->where('did',$ids)->select();
            $this->assign('yijian',$yijian);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $params['car_is_new'] = isset($params['car_is_new']) ? $params['car_is_new'] : 2;
            $params['main_franchise'] = isset($params['main_franchise']) ? $params['main_franchise'] : 2;
            $params['main_ji'] = isset($params['main_ji']) ? $params['main_ji'] : 2;
            $params['dao_ji'] = isset($params['dao_ji']) ? $params['dao_ji'] : 2;
            $params['siji_ji'] = isset($params['siji_ji']) ? $params['siji_ji'] : 2;
            $params['ck_ji'] = isset($params['ck_ji']) ? $params['ck_ji'] : 2;
            $params['dw_ji'] = isset($params['dw_ji']) ? $params['dw_ji'] : 2;
            $params['main_name'] = isset($params['main_name']) ? $params['main_name'] : 2;
            $params['main_disan'] = isset($params['main_disan']) ? $params['main_disan'] : 2;
            $params['dao_name'] = isset($params['dao_name']) ? $params['dao_name'] : 2;
            $params['siji'] = isset($params['siji']) ? $params['siji'] : 2;
            $params['chengke'] = isset($params['chengke']) ? $params['chengke'] : 2;
            $params['dianwang'] = isset($params['dianwang']) ? $params['dianwang'] : 2;

            $params['status'] = 0;
            $params['car_register'] = strtotime($params['car_register']);
            $params['plan_strattime'] = strtotime($params['plan_strattime']);
            $params['plan_endtime'] = strtotime($params['plan_endtime']);
            $params['yw_join_time'] = time();
            if($row['main_sumdiscount'] != $params['main_sumdiscount']){
                $params['kehu_sumdiscount'] = $params['main_sumdiscount'];
            }
            $urls = $params['file'];
            unset($params['file']);
            if($status == 1){
                //判断车架号是否符合服务
//                $isset = Db::name('list_one')->where('car_vin',$params['car_vin'])->where('status','in',[1,3])->where('deletetime',)->field('id,status,plan_endtime')->find();
//                if($isset){
//                    $this->error('该车正在服务中，不得重复添加');
//                }
                $params['main_xiaoguan_bili'] = 0;
                $params['main_yunying_bili'] = 0;
                $params['main_netrate'] = 40;
                $params['status'] =1;
                $params['yw_hetong_time'] = time();
            }else{
//                $count = Db::name('list_one')->where('learned_phone',$params['learned_phone'])->where('status','in',[0,1,3,5])->where('deletetime',)->field('id,status,plan_endtime')->count();
//                if($count > 2){
//                    $this->error('当前手机号超过两次，不可录入');
//                }
            }
            $result = $row->allowField(true)->save($params);
            $this->saveFile($ids, $urls);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getSubs1($categorys, $catId = 0, $level = 1)
    {
        $ids = array(); // 用于存储所有 id
        foreach ($categorys as $item) {
            if ($item['pid'] == $catId) {
                $ids[] = $item['id']; // 收集当前 id
                // 递归调用，确保总是返回数组
                $childIds = $this->getSubs1($categorys, $item['id'], $level + 1);
                if (is_array($childIds)) {
                    $ids = array_merge($ids, $childIds);
                }
            }
        }
        return $ids; // 返回 id 数组
    }
    function getSubs($categorys,$catId=0,$level=1){
        $subs=array();
        foreach($categorys as $item){
            if($item['pid']==$catId){
                $item['level']=$level;
                $subs[]=$item;
                $subs=array_merge($subs,$this->getSubs($categorys,$item['id'],$level+1));
            }
        }
        return $subs;
    }


    /**
     * 处理上传照片
     * @param $id
     * @param $urls
     * @return false|int|string
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException\
     */
    public function saveFile($id, $urls) {
        // 会有重复的可能，需要处理
        $olds = db('tong_files')->where('tong_id', $id)->select();
        $newid = $id;
        $res = db('tong_files')->where('tong_id', $id)->delete();
        $urls = explode(',', $urls);
        $count = count($urls);
        $res = false;
        for ($i=0;$i<$count;$i++){
            $img['url'] = $urls[$i];
            $img['tong_id'] = $newid;
            $img['title'] = '';
            $img['updatetime'] = time();
            $res = db('tong_files')->insert($img);
        }

        return $res;
    }


    /**
     * 处理时间
     * @return void
     */
    public function datecount(){
        $data = input('get.');
        $time = strtotime($data['time']);
        $end_time = strtotime($data['end_time']);
        $datecount = round(bcdiv(bcsub($end_time,$time),86400,4));
        $this->success('','',$datecount);
    }

    /**
     * 获取折扣
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     *
     */
    public function select()
    {
        $post = input('post.');
        $post['type'] = preg_replace('/-\d+$/', '', $post['type']);  // 正则表达式去除最后的“-数字”
        $where['zuzhi_id'] = $post['zuzhi_id'];
        $where['type'] = $post['type'];
        $listname = db('zhekou')->where($where)->select();
        if(!$listname){
            $listname = db('zhekou')->where('zuzhi_id',1)->where('type',$post['type'])->select();
        }
        $arr = [];
        $i = 0;
        foreach($listname as $k => $v){
            $arr[$i] = $v;
// 			$i++;

            $i++;
        }
// 		dump(123);die;
        foreach($listname as $k => $v){
            $v['ncd'] = $v['ncd'].'(不含车损)';
            if($v['no_zhekou']){
                $v['zhekou'] = $v['no_zhekou'];
            }

            $arr[$i] = $v;
            $i++;
        }
// 		dump($arr);die;
        return json(['data'=>$arr]);
    }


    public function ywclass(){
        $data = $_POST;
        $res = db('admin')->where($data)->select();
        $cateid = $data['zuzhi'];
        $date = db('zuzhi')->where('delete_id',0)->select();
        $arr = $this->frontdels($date,$cateid);
        $arr[] = (int)$cateid;
        $ren = db('admin')->where('zuzhi','in',$arr)->select();
        $rens = db('admin')->where('zuzhi',$cateid)->select();
        return json(['ren'=>$ren,'rens'=>$rens]);
    }
    public function frontdels($data,$cateid){
        //var_dump($data);die();
        static $arr=array();
        foreach ($data as $key => $v) {
            if($v["pid"]==$cateid){
                $arr[]=$v['id'];
                $this->frontdels($data,$v['id']);
            }
        }
        return $arr;
    }
    /*
    * 重新签名
    * @return mixed
    */
    public function chong_qian()
    {
        $data = input('post.');
        db('sign')->where(['orderid'=>$data['id']])->delete();
        return ["status"=>200,"message"=>'成功'];
    }

    /**
     * 浏览
     * @param $ids
     * @return void
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function details($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['car_register'] = date('Y-m-d',$row['car_register']);
        $row['plan_strattime'] = date('Y-m-d H:i:s',$row['plan_strattime']);
        $row['plan_endtime'] = date('Y-m-d H:i:s',$row['plan_endtime']);
        $this->view->assign('row', $row);
        $select = selectMenus_zuzhi($admin['zuzhi']);
        $this->assign('selectMenu',$select);
        $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
        $this->assign('ren',$ren);
        $ying = db('tong_files')->where('tong_id',$ids)->select();
        $this->assign('file', $ying);

        $yijian = db('yijian')->where('did',$ids)->select();
        $this->assign('yijian',$yijian);
        return $this->view->fetch();
    }

    /**
     * 报价单信息查询
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function baojiadan(){

        //查询
        $data = input('post.');
        $id = $data['id'];
        // $where[] = ['id'=>$id];
        $res = Db::name('list_one')->where('id', $id)->where('deletetime',)->find();
        $res['car_use_natures'] = model('Constants')->CAR_USE_NATURE[$res['car_use_nature']];
        $res['yw_join_time'] = $res['yw_join_time'] ? date("Y-m-d",$res['yw_join_time']) : date('Y-m-d');
        if (!isset($data['lei']) && ($res['jiaofei'] == 1)) {
            //判断暂存单号是否是今天的
            $time = substr($res['tong_storage'], 0, 4) . '-' . substr($res['tong_storage'], 4, 2) . '-' . substr($res['tong_storage'], 6, 2);
            if (date('Y-m-d', time()) <> $time) {
                $zancun = zancun("list_one", "tong_storage", "");
                //修改
                Db::name('list_one')->where('id', $id)->update(['tong_storage' => $zancun]);
                $res['tong_storage'] = $zancun;
            }
        }
        $res['plan_strattime'] = date("Y-m-d H:i:s", $res['plan_strattime']);
        $res['plan_endtime'] = date("Y-m-d H:i:s", $res['plan_endtime']);
//        if ($res['kehu_sumdiscount'] != $res['main_sumdiscount']) {
//            $res['main_sumdiscount'] = $res['kehu_sumdiscount'];
//            $main_sum = $res['main_sum'];
//            if ($res['dao_name'] == 1) {
//                $main_sum = bcsub($main_sum, $res['dao_ying'], 2);
//            }
//            if ($res['dianwang'] == 1) {
//                $main_sum = bcsub($main_sum, $res['dao_ying'], 2);
//            }
//            $kehu_tongchou = round(bcdiv(bcmul($res['kehu_sumdiscount'], $main_sum, 2), 100, 4), 2);
//            if ($res['dao_name'] == 1) {
//                $kehu_tongchou = bcadd($kehu_tongchou, $res['dao_ying'], 2);
//            }
//            if ($res['dianwang'] == 1) {
//                $kehu_tongchou = bcadd($kehu_tongchou, $res['dw_ying'], 2);
//            }
//            $res['main_free'] = $kehu_tongchou;
//        }
        $res['car_register'] = date('Y-m-d', $res['car_register']);
//        $res['v'] = $this->conf_lei($res);
//        $res['car_use_nature_str'] = $this->car_use_nature_str($res['car_use_nature']);
        //获取年龄和性别
//        $res['age'] = '';
//        $res['sex'] = '';
//        $pattern = '/^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/';
//        if($res['car_card_kind'] == 0 && $res['car_card'] && preg_match($pattern, $res['car_card'])){
//            $year = substr($res['car_card'], 6, 4);//获取身份证出生年
//            $res['age'] = date('Y') - $year;//当前年减去身份证年
//            $res['sex'] = substr($res['car_card'], (strlen($res['car_card'])==18 ? -2 : -1), 1) % 2 ? '男' : '女';
//        }
        $res['bjd_bgs'] = thconfig::get('site.bjd_bgs');
        $this->success('','',$res);
    }
    public function conf_lei($res)
    {
        $v = '';
        $k = 0;
        if ($res['main_standard']) {
            if ($k <> 0) {
                $v .= '|';
            }
            $v .= '车损';
            $k++;
        }
        if ($res['main_biao']) {
            if ($k <> 0) {
                $v .= '|';
            }
            $v .= '三者' . $this->convertTo($res['main_santong']);
            $k++;
        }
        if ($res['siji_biao']) {
            if ($k <> 0) {
                $v .= '|';
            }
            $v .= '司机' . $this->convertTo($res['siji_tong']);
            $k++;
        }
        if ($res['ck_biao']) {
            if ($k <> 0) {
                $v .= '|';
            }
            $v .= '乘客' . $this->convertTo($res['ck_tong']);
            $k++;
        }
        if ($res['dao_biao']) {
            if ($k <> 0) {
                $v .= '|';
            }
            $v .= '三者医保外用药' . $this->convertTo($res['dao_tong']);
            $k++;
        }
        return $v;
    }
    public function convertTo($number)
    {
        return number_format(floatval($number) / 10000, 0) . '万元';
    }
    public function car_use_nature_str($value) {
        try {
            return model('Constants')->CAR_USE_NATURE[$value];
        } catch (Exception $e) {
            return '';
        }
    }

    //更新暂存单号
    public function up_danahao($ids = null)
    {
        //查询
        if(!$ids) $this->error('参数错误');
        $id = $ids;
        $res =  Db::name('list_one')->where('id',$id)->where('deletetime',)->find();
        if($res['jiaofei'] == 1){
            //判断暂存单号是否是今天的
            $zancun = zancun("list_one", "tong_storage", "");
            //修改
            Db::name('list_one')->where('id',$id)->update(['tong_storage'=>$zancun,'openid'=>'']);
            $res['tong_storage'] = $zancun;
            $this->success('成功');
        }else{
            $this->error('错误');
        }
    }
    // 管理员取消
    // TODO: 记录日志
    public  function quxiao_admin($ids = null){
        $id = $ids;
        if(empty($id)){
            $this->error('请先选择要操作的对象');
        }else{
            $res = Db::name('list_one')->where('id',$id)->update(['status'=>4,'tong_number'=>null]);
            if($res){
                $this->success('成功');
            }else{
                $this->error('操作失败');
            }
        }
    }
    //查询页面取消通过操作
    public  function quxiao($ids = null){
        $id = $ids;
        $ress = Db::name('list_one')->where('id',$id)->find();
        if(empty($id)){
            $this->error('请先选择要操作的对象');
        }elseif($ress['status'] == 5){
            $this->error('已生成服务单,不可进行操作');
        }else{
            $res = Db::name('list_one')->where('id',$id)->update(['status'=>4]);
            if($res){
                $this->success('成功');
            }else{
                $this->error('操作失败');
            }

        }
    }

    /**
     * 电子服务单
     * @return mixed|void
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public  function dian($ids = null){
        $id = $ids;
        if(empty($id)){
            $id = $_GET['one_id'];
        }
        if(empty($id)){
            $this->error('请先选择要生成服务单的对象');
        }else{
            $res = Db::name('list_one')->where('id',$id)->where('deletetime',)->find();
            $res['car_use_nature_str'] = $this->car_use_nature_str($res['car_use_nature']);
            $tc_list = array();
            $k=0;
            $line = 8;
            if($res['main_standard']){
                $tc_list[$k]['tczl']='机动车车损损失';
                $tc_list[$k]['bjmp'] = $res['main_franchise'];
                $tc_list[$k]['money']= $res['main_money'];
                $tc_list[$k]['tcf']= $res['main_submit'];
//                if($res['kehu_sumdiscount']){
//                    $tc_list[$k]['tcf'] = round(bcdiv(bcmul((float)$res['kehu_sumdiscount'],(float)$res['main_standard'],2),100,4),2);
//                }

                $k=$k+1;
            }
            if($res['main_biao']){
                $tc_list[$k]['tczl']='机动车第三者责任';
                $tc_list[$k]['bjmp'] = $res['main_ji'];
                $tc_list[$k]['money']= $res['main_santong'];
                $tc_list[$k]['tcf']= $res['main_yingjiao'];
//                if($res['kehu_sumdiscount']){
//                    $tc_list[$k]['tcf'] = round(bcdiv(bcmul((float)$res['kehu_sumdiscount'],(float)$res['main_biao'],2),100,4),2);
//                }
                $k=$k+1;
            }
            if($res['dao_biao']){
                $tc_list[$k]['tczl']='医保外用药';
                $tc_list[$k]['bjmp'] = $res['dao_ji'];
                $tc_list[$k]['money']= $res['dao_tong'];
                $tc_list[$k]['tcf']= $res['dao_ying'];
                $k=$k+1;
            }
            if($res['siji_biao']){
                $tc_list[$k]['tczl']='机动车车上人员-司机 *1';
                $tc_list[$k]['bjmp'] = $res['siji_ji'];
                $tc_list[$k]['money']= $res['siji_tong'];
                $tc_list[$k]['tcf']= $res['siji_ying'];
//                if($res['kehu_sumdiscount']){
//                    $tc_list[$k]['tcf'] = round(bcdiv(bcmul((float)$res['kehu_sumdiscount'],(float)$res['siji_biao'],2),100,4),2);
//                }
                $k=$k+1;
            }
            if($res['ck_biao']){
                $tc_list[$k]['tczl']='机动车车上人员-乘客 * ' . (string)($res['car_carry_peo'] - 1);
                $tc_list[$k]['bjmp'] = $res['ck_ji'];
//                $tc_list[$k]['money']= $res['ck_tong'];
                $tc_list[$k]['money']= $res['ck_money']. ' * '.(string)($res['car_carry_peo'] - 1);
                $tc_list[$k]['tcf']= $res['ck_ying'];
//                if($res['kehu_sumdiscount']){
//                    $tc_list[$k]['tcf'] = round(bcdiv(bcmul((float)$res['kehu_sumdiscount'],(float)$res['ck_biao'],2),100,4),2);
//                }
                $k=$k+1;
            }
            if($res['dw_biao']){
                $tc_list[$k]['tczl']='外部电网故障损失';
                $tc_list[$k]['bjmp'] = $res['dw_ji'];
                $tc_list[$k]['money']= $res['dw_tong'];
                $tc_list[$k]['tcf']= $res['dw_ying'];
                $k=$k+1;
            }
            if($res['zi_biao']){
                //	$tc_list[$k]['tczl']='自燃损失统筹';
                $tc_list[$k]['tczl']=$res['ziran_c'];
                $tc_list[$k]['bjmp'] = $res['zi_buji'];
                $tc_list[$k]['money']= $res['zi_tong'];
                $tc_list[$k]['tcf']= $res['zi_ying'];
                $k=$k+1;
            }
//            dump($tc_list);die;
            if($res['fdj_biao']){
                //	$tc_list[$k]['tczl']='发动机涉水损失统筹';
                $tc_list[$k]['tczl']=$res['fd_c'];
                $tc_list[$k]['bjmp'] = $res['fdj_buji'];
                $tc_list[$k]['money']= $res['fdj_tong'];
                $tc_list[$k]['tcf']= $res['fdj_ying'];
                $k=$k+1;
            }

            if($res['zd_biao']){
                $tc_list[$k]['tczl']=$res['zd_c'];
                $tc_list[$k]['bjmp'] = $res['zd_buji'];
                $tc_list[$k]['money']= $res['zd_tong'];
                $tc_list[$k]['tcf']= $res['zd_ying'];
                $k=$k+1;
            }
            if($res['hw_biao']){
                $tc_list[$k]['tczl']=$res['huowu_c'];
                $tc_list[$k]['bjmp'] = $res['hw_buji'];
                $tc_list[$k]['money']= $res['hw_tong'];
                $tc_list[$k]['tcf']= $res['hw_ying'];
                $k=$k+1;
            }
            if($res['bl_biao']){
                $tc_list[$k]['tczl']=$res['bili_c'];
                $tc_list[$k]['bjmp'] = $res['bl_buji'];
                $tc_list[$k]['money']= $res['bl_tong'];
                $tc_list[$k]['tcf']= $res['bl_ying'];
                $k=$k+1;
            }
            if($res['bl_biao']){
                $tc_list[$k]['tczl']=$res['bili_c'];
                $tc_list[$k]['bjmp'] = $res['bl_buji'];
                $tc_list[$k]['money']= $res['bl_tong'];
                $tc_list[$k]['tcf']= $res['bl_ying'];
                $k=$k+1;
            }
            $site = \think\Config::get('site');
            $site['chexing']['6座以下.'] = '6座以下';
            $res['chexing'] = array_flip($site['chexing'])[$res['chexing']];
            $line = $line - $k;
            $this->assign('tc_list',$tc_list);
            $this->assign('line',$line);
//            if($res['kehu_sumdiscount'] != $res['main_sumdiscount']){
//                $main_sum = 0;
//                if($res['main_name'] == 1){
//                    $main_sum = bcadd($main_sum,round(bcmul(floatval($res['main_standard']),bcdiv($res['kehu_sumdiscount'],100,2),4),2),2);
//                }
//                if($res['main_disan'] == 1){
//                    $main_sum = bcadd($main_sum,round(bcmul(floatval($res['main_biao']),bcdiv($res['kehu_sumdiscount'],100,2),4),2),2);
//                }
//
//                if($res['siji'] == 1){
//                    $main_sum = bcadd($main_sum,round(bcmul(floatval($res['siji_biao']),bcdiv($res['kehu_sumdiscount'],100,2),4),2),2);
//                }
//
//                if($res['chengke'] == 1){
//                    $main_sum = bcadd($main_sum,round(bcmul(floatval($res['ck_biao']),bcdiv($res['kehu_sumdiscount'],100,2),4),2),2);
//                }
//
//                if($res['ziran'] == 1){
//                    $main_sum = bcadd($main_sum,round(bcmul(floatval($res['zi_biao']),bcdiv($res['kehu_sumdiscount'],100,2),4),2),2);
//                }
//                if($res['dao_name'] == 1){
//                    $main_sum = bcadd($main_sum,$res['dao_ying'],2);
//                }
//                $res['main_free'] = $main_sum;
//            }
            $this->assign('res',$res);
            $tiaokuan = db('tiaokuan')->order('id desc')->where(['gs_type'=>1])->limit(1)->find();
            $this->assign('tiaokuan',$tiaokuan);
            // 临时关闭当前模板的布局功能
            $sign = Db::name('sign')->where('orderid',$id)->find();
            $this->assign('sign',$sign);
            $this->view->engine->layout(false);
            return $this->fetch('dian');
        }
    }
    //补录页面
    public function bulu($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $dataOne = Db::name('list_one')->where('id',$ids)->where('deletetime',)->find();
            $this->assign('res',$dataOne);
            $ying = db('tong_files')->where('tong_id',$ids)->column('url');
            $this->assign('file', implode(',',$ying));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = true;
        Db::startTrans();
        try {
            //是否采用模型验证
            $urls = $params['file'];
            $result = $this->saveFile($ids, $urls);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function new_baojiadan(){
        $data = input('post.');
        //判断签字状态
        $list_one = Db::name('list_one')->where(['id'=>$data['id']])->where('deletetime',)->find();
        if($list_one['qianzi_status'] == 1){
            Db::name('list_one')->where(['id'=>$data['id']])->update(['qianzi_status'=>2]);
        }
        //查询签字
        $sign = Db::name('sign')->where(['orderid'=>$data['id']])->find();
        $list_one['sign'] = $sign;
        //生成二维码
        $zhifubao = openssl_encrypt($list_one['id'], 'AES-128-ECB', 'zhifubao', OPENSSL_RAW_DATA);
        $zhifubao = base64_encode($zhifubao);
        $weixin = openssl_encrypt($list_one['id'], 'AES-128-ECB', 'weixin', OPENSSL_RAW_DATA);
        $weixin = base64_encode($weixin);
        $zhifubao = str_replace('%','%25',$zhifubao);
        $zhifubao = str_replace('+','%2B',$zhifubao);
        $zhifubao = str_replace(' ','%20',$zhifubao);
        $zhifubao = str_replace('/','%2F',$zhifubao);
        $zhifubao = str_replace('?','%3F',$zhifubao);
        $zhifubao = str_replace('#','%23',$zhifubao);
        $zhifubao = str_replace('&','%26',$zhifubao);
        $zhifubao = str_replace('=','%3D',$zhifubao);
        //展示日期
        $time = date('Y-m-d');
        $time = openssl_encrypt($time, 'AES-128-ECB', 'ming', OPENSSL_RAW_DATA);
        $time = base64_encode($time);
        $time = str_replace('%','%25',$time);
        $time = str_replace('+','%2B',$time);
        $time = str_replace(' ','%20',$time);
        $time = str_replace('/','%2F',$time);
        $time = str_replace('?','%3F',$time);
        $time = str_replace('#','%23',$time);
        $time = str_replace('&','%26',$time);
        $time = str_replace('=','%3D',$time);
        vendor("phpqrcode.phpqrcode");
        if(isset($data['channel_id'])){
            $value = $this->request->scheme().'://'.$this->request->host().'/index/index/new_zhifu?id='.$zhifubao.'&time='.$time.'&channel_id='.$data['channel_id'];//二维码内容
        }else{
            $value = '';//二维码内容
        }
        $errorCorrectionLevel = 'L';	//容错级别
        $matrixPointSize = 5;			//生成图片大小
        $u =new \QRcode();
        //生成二维码图片
        ob_start();//开启缓冲区
        $QR = \QRcode::png($value,false,$errorCorrectionLevel, $matrixPointSize, 2);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean(); //清除缓冲区的内容，并将缓冲区关闭，但不会输出内容

        $list_one['zhifubao'] = $zhifubao;
        $list_one['weixin'] = $weixin;
        $list_one['times'] = date('Y-m-d').' 23:59:59';

        $list_one['er'] = "data:image/jpg;base64,".$imageString;

        if(isset($data['channel_id'])){
            $pay_channel = Db::name('pay_channel')->where(['id'=>$data['channel_id']])->find();
            if($pay_channel['type_id'] == 6){
                $list_one['er'] = $pay_channel['image'];
            }
        }

//        if($list_one['jq_price']){
//            $list_one['main_free'] = bcadd (floatval($list_one['jq_price']),floatval($list_one['main_free']),2);
//        }
//        if($list_one['cc_price']){
//            $list_one['main_free'] = bcadd (floatval($list_one['cc_price']),floatval($list_one['main_free']),2);
//        }
        return json(['code'=>1,'msg'=>'查询成功','data'=>$list_one]);
    }

    /**
     *
     * @return mixed
     */
    //信息查询页面
    public function tk_type(){

        //查询
        $data = input('post.');

        $id = $data['id'];
        Db::name('list_one')->where(['id'=>$id])->update(['tk_type'=>$data['type']]);
        return json(['code'=>1]);
    }
    /**
     *
     * @return mixed
     */
    //信息查询页面
    public function bjt(){

        //查询
        $data = input('post.');

        $id = $data['id'];
        Db::name('list_one')->where(['id'=>$id])->update(['bjt'=>$data['type']]);
        return json(['code'=>1]);
    }

    public function tcxm(){

        //查询
        $data = input('post.');
        $id = $data['id'];
        Db::name('list_one')->where(['id'=>$id])->update(['tcxm'=>$data['type']]);

    }

    /**
     *
     * @return mixed
     */
    //信息查询页面
    public function chezhu(){

        //查询
        $data = input('post.');
        $id = $data['id'];
        $info = Db::name('list_one')->where(['id'=>$id])->field('learned_name,car_owner')->find();
        Db::name('list_one')->where(['id'=>$id])->update(['chezhu'=>$data['type']]);
        return json(['code'=>1,'data'=>$info]);
    }

    public function zuzhi(){
        $admin = $this->auth->getUserInfo();
        $cateid = $admin['zuzhi'];
        if($keyvalue = $this->request->request("name")){
            $res = Db::name('zuzhi')->where('name','like',"%$keyvalue%")->where('delete_id',0)->select();
        }else{
            $res = Db::name('zuzhi')->where('delete_id',0)->select();
        }
        $arr_all = $this->getSubs1($res, $cateid);
        $arr_all[] = $cateid;
        $select = db('zuzhi')
            ->where('id','in',$arr_all)
            ->select();
        $select = Loader::model('Zuzhi')->selectMenus_res($select);
        return ['list'=>$select];
    }
    public function select_zuzhi(){
        $admin = $this->auth->getUserInfo();
        $select = Loader::model('Zuzhi')->selectMenus($admin['zuzhi']);
        return $select;

    }
    public  function baojiadan_new()
    {
        //查询
        $data = input('get.');
        $id = $data['id'];
        $row = Db::name('list_one')->where('id', $id)->where('deletetime',)->find();
        if(!$row){
            $row['tpsss'] = 1;
        }else{
            $row['plan_strattime'] = date("Y-m-d H:i:s", $row['plan_strattime']);
            $row['plan_endtime']   = date("Y-m-d H:i:s", $row['plan_endtime']);

            $row['car_register'] = date('Y-m-d', $row['car_register']);
            $row['tpsss'] = 2;
        }
        $this->assign('timess', date('Y-m-d'));
        $this->assign('row', $row);
        return $this->fetch();
    }
    //查询被服务人
    public function learned_info(){
        $data = input('post.');
        $learned_name = $data['learned_name'];
        $res = Db::name('list_one')->where('learned_name',$learned_name)->where('status','5')->where('deletetime',)->find();
        $msg = '';
        if($res){
            $status = 1;
        }else{
            $status = 0;
            $msg = '暂无客户信息！';
        }
        return json(['status'=>$status,'msg'=>$msg]);
    }
    //查询被服务人信息列表
    public function learned_list(){
        $data = input('get.');
        $learned_name = $data['learned_name'];
        $res =  Db::name('list_one')->field('id,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address')
            ->where('learned_name',$learned_name)->where('status','5')->where('deletetime',)->order('id desc')->select();
        $res = $this->array_unset_tt($res,'learned_num');
        $this->assign('res',$res);
        // 临时关闭当前模板的布局功能
        $this->view->engine->layout(false);
        return $this->fetch("learned_list");
    }

    //查询车辆信息
    public function car_num_info(){
        $data = input('post.');
        $car_num = $data['car_num'];
        $res = Db::name('list_one')->where('car_num',$car_num)->where('status','5')->field('id,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address')->where('deletetime',)->find();

        $isset = Db::name('list_one')->where('car_num',$data['car_num'])->where('deletetime',)->where('status','in',[0,1,2,3,4])->field('id,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address,status')->find();

        if($isset){
            if($isset['status'] == 0){
                return ["status"=>500,"msg"=>'该车暂存中，不得重复添加'];
            }
            return ["status"=>500,"msg"=>'该车正在服务中，不得重复添加'];
        }
        $isset2 = Db::name('list_one')->where('car_num',$data['car_num'])->where('deletetime',)->where('status',5)->field('id,status,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address,plan_endtime')->select();
        foreach ($isset2 as $key => $value) {
            if($value['status']==5){
                if($value['plan_endtime']>time()){
                    return ["status"=>500,"msg"=>'该车正在服务中，不得重复添加'];
                }
            }
        }

        $isset3 = Db::name('list_one_old')->where('car_num',$data['car_num'])->where('status',5)->field('id,status,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address,plan_endtime')->select();
        foreach ($isset3 as $key => $value1) {
            if($value1['status']==5){
                if($value1['plan_endtime']>time()){
                    return ["status"=>500,"msg"=>'旧系统中正在服务中，不得重复添加'];
                }
            }
        }
        $msg = '';
        if($res){
            $status = 1;
        }else{
            $status = 0;
            $msg = '暂无车辆信息！';
        }
        return json(['status'=>$status,'msg'=>$msg]);
    }
    //查询车辆信息列表
    public function car_num_list(){
        $data = input('get.');
        $car_num = $data['car_num'];
        $res =  Db::name('list_one')->where('car_num',$car_num)->where('deletetime',)->where('status','5')->order('id desc')->select();
        $this->assign('res',$res);
        // 临时关闭当前模板的布局功能
        $this->view->engine->layout(false);
        return $this->fetch("car_num_list");
    }
    //多维数组 指定字段去重
    function array_unset_tt($arr,$key=''){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                unset($value[$key]);  //有：销毁
            }else{
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function xubao($ids = null,$status = 0)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['car_register'] = date('Y-m-d',$row['car_register']);
            if($row['plan_endtime'] > time()){
                $row['plan_strattime'] = date('Y-m-d H:i:s',$row['plan_endtime']+86401);
                $row['plan_endtime'] = date('Y-m-d H:i:s', strtotime('+1 year', $row['plan_strattime']-1));
            }else{
                $row['plan_strattime'] = date('Y-m-d 00:00:00',strtotime('+1 day'));
                $row['plan_endtime'] = date('Y-m-d H:i:s', strtotime('+1 year', $row['plan_strattime']-1));
            }
            $this->view->assign('row', $row);
            $select = selectMenus_zuzhi($admin['zuzhi']);
            $this->assign('selectMenu',$select);
            $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
            $this->assign('ren',$ren);
            $ying =   $ying = db('tong_files')->where('tong_id',$ids)->column('url');
            $this->assign('file', implode(',',$ying));
            $yijian = db('yijian')->where('did',$ids)->select();
            $this->assign('yijian',$yijian);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //1、获取本商户的最新进货单号
            $zancun = zancun("list_one", "tong_storage", "");
            $params['tong_storage'] = $zancun;
            $params['kehu_sumdiscount'] = $params['main_sumdiscount'];
            $urls = $params['file'];
            unset($params['file']);
            $params['status'] = 0;
            $params['car_register'] = strtotime($params['car_register']);
            $params['plan_strattime'] = strtotime($params['plan_strattime']);
            $params['plan_endtime'] = strtotime($params['plan_endtime']);
            $params['yw_join_time'] = time();
            $params['yw_enter_peo'] = $admin['username'];
//            $params['chexing_ci'] = $params['c-chexing_ci'];
//            unset($params['c-chexing_ci']);
//            $car_num = $params['car_num'];
//            $car_vin = $params['car_vin'];
//            $car_engine = $params['car_engine'];
//            $where = "car_num='{$car_num}' OR car_vin='{$car_vin}'";
//            if ($car_engine != "无") {
//                $where .= " OR car_engine='{$car_engine}'";
//            }
//            $dong_list = Db::name("list_one")->where($where)->where('deletetime',)->field('id,plan_endtime')->select();
//            $dong_error = false;
//            foreach ($dong_list as $item) {
//                if ($item['plan_endtime'] > $params['plan_strattime']) {
//                    $dong_error = true;
//                    break;
//                }
//            }
//            if ($dong_error) {
            // return ["status" => 0, "message" => "服务日期重叠"];
//            }

            $params['user_id'] = $admin['id'];
            $params['yw_handle'] = $admin['username'];
            $result = db('list_one')->insertGetId($params);
            $id = $result;
            $newid = $id;
            $urls = explode(',', $urls);
            $count = count($urls);
            for ($i=0;$i<$count;$i++){
                $img['url'] = $urls[$i];
                $img['tong_id'] = $newid;
                $img['title'] = '';
                $img['updatetime'] = time();
                $res = db('tong_files')->insert($img);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocr Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 2、访问的域名。注意：这个地方需要求改为相应类目的域名，参考：https://help.aliyun.com/document_detail/143103.html
        $config->endpoint = "ocr.cn-shanghai.aliyuncs.com";
        // 3、这里只是以ocr为例，其他能力请引入相应类目的Client类
        return new Ocr($config);
    }
    /**
     * @param string[] $args
     * @return void
     */
    public static function main() {
        // dump($_POST);die;
        $url = $_POST['url'];
        // 4、"YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET" 的生成请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您是用的子账号AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        $client = self::createClient("LTAI5t9cCgaEBy1fZ4RR3oAh", "JS3nXlvYDZim7FGoTqwvrq48oZ0TKY");
        $runtime = new RuntimeOptions([]);
        // 5、这里只是以ocr下的RecognizeBankCard为例，其他能力请使用相应类目的包和类，具体入参设置需要参考具体能力的文档
        $recognizeBankCardAdvanceRequest = new RecognizeBankCardAdvanceRequest();
        // 场景一，使用本地文件

        // dump($_SERVER['HTTP_HOST'].'/QQ20230307-145352@2x.png');die;
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        // dump($http_type . $_SERVER['HTTP_HOST'].$url);die;
        $file = fopen($http_type . $_SERVER['HTTP_HOST'].$url, 'rb');
        // $file = fopen('https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeIdentityCard/sfzbm1.jpg', 'rb');
        $stream = new Stream($file);

        $runtime = new RuntimeOptions([]);
        try {
            if($_POST['type'] == 1){
                $recognizeIdentityCardAdvanceRequest = new RecognizeIdentityCardAdvanceRequest([
                    "imageURLObject" => $stream,
                    "side" => "face"
                ]);
                $resp = $client->recognizeIdentityCardAdvance($recognizeIdentityCardAdvanceRequest, $runtime);
            }else{
                $recognizeDrivingLicenseRequest = new RecognizeDrivingLicenseAdvanceRequest([
                    "side" => "face",
                    "imageURLObject" => $stream
                ]);
                // dump($stream);die;
                $resp = $client->recognizeDrivingLicenseAdvance($recognizeDrivingLicenseRequest, $runtime);
            }
            // dump($resp);die;
            # 获取整体结果

            // echo Utils::toJSONString($resp->body);
            $data = json_decode(json_encode($resp),true);
            return json(['msg'=>'识别成功','data'=>$data['data']]);
            // dump($data['data']['frontResult']);
            // faceResult
        } catch (Exception $error) {
            // # 获取整体报错信息
            // echo Utils::toJSONString($exception);
            // # 获取单个字段
            // echo $exception->getCode();
            // if (!($error instanceof TeaError)) {
            //     $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            // }
            // 如有需要，请打印 error
            // Utils::assertAsString($error->message);
            return json(['msg'=>$error->getCode()]);
        }
    }

    public function kaipiao($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->assign('row',$row);
            $this->assign('file', $row['invoice_img']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = true;
        Db::startTrans();
        try {
            //是否采用模型验证
            $result = Db::name('list_one')->where('id',$ids)->update(['invoice_kind'=>$params['invoice_kind'],'invoice_beizhu'=>$params['invoice_beizhu'],'invoice_img'=>$params['file']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 服务单信息
     * @param $ids
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function baoan($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $car_vin = $this->request->get('car_vin');
        if ($this->request->isAjax()) {

            $this->model = new Baoan();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $buchang_money =  $this->model
                ->where($where)
                ->sum('buchang_money');
            $yugu_money = $this->model->where($where)->sum('yufu');
            $weijue_money = bcsub($yugu_money,$buchang_money,2);
            $result = array("total" => $list->total(), "rows" => $list->items(),'buchang_money'=>$buchang_money,'weijue_money'=>$weijue_money);

            return json($result);
        }else{
            $this->view->assign("car_vin", $car_vin);
            return $this->view->fetch();
        }
    }

    /**
     * 详情
     * @param $ids
     * @return void
     * @throws \think\exception\DbException
     */
    public function baoan_details($ids = null)
    {
        $this->model = new Baoan();
        $row = $this->model->get(['id' => $ids]);
        $row['yw_class'] = Db::name('zuzhi')->where('id', $row['yw_class'])->value('name');
        $this->assign('row', $row);
        return $this->view->fetch();
    }


    public function jiaofei(){
        $data = input('post.');
        //判断签字状态
        $list_one = Db::name('list_one')->where(['id'=>$data['id']])->where('deletetime',)->find();
        if($list_one['zhifu']){
            $zuzhi['pay_channel_id'] = $list_one['zhifu'];
            $pay_channel = pay_type($zuzhi);
            $this->success('','',$pay_channel);
        }else{
            $this->success('','',[]);
        }
    }

    public function chexing(){

        $site = thconfig::get('site');
        $chexing = [];
        foreach ($site['chexing'] as $k => $v){
            $chexing[$v] = $k;
        }
        return json($chexing);
    }
}
